﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
using System.IO;
using System.Text;
using Microsoft.Phone.Net.NetworkInformation;
using System.Windows.Media.Imaging;
using System.Windows.Controls.Primitives;

namespace NearChat
{
    public partial class Profilo : PhoneApplicationPage
    {
        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        private string idUser;
        private string imageURL;

        public Profilo()
        {
            InitializeComponent();

            //disabilito e nascondo i pulsanti
            buttonModifica.Visibility = System.Windows.Visibility.Collapsed;
            buttonModifica.IsEnabled = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string idout = string.Empty;
            if (NavigationContext.QueryString.TryGetValue("ID", out idout))
                idUser = idout;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if ((idUser == appSettings["ID"].ToString()) && NetworkInterface.GetIsNetworkAvailable())//sono io e c'è rete
            {
                //abilito il tasto modifica
                buttonModifica.Visibility = System.Windows.Visibility.Visible;
                buttonModifica.IsEnabled = true;
            }

            if ((idUser == appSettings["ID"].ToString()) && appSettings.Contains("sesso"))//è il posssessore e conosce già i suoi dati
            {
                //non serve fare la query, carico direttamente i dati
                NameText.Text = appSettings["user"].ToString();
                InfoText.Text = appSettings["sesso"] + " " + appSettings["nascita"];

                imageURL = appSettings["image"].ToString(); ; //l'URL della mia immagine
                BitmapImage urlProfilo = new BitmapImage(new Uri(imageURL, UriKind.Absolute));
                ImageBrush sfondo = new ImageBrush();
                ImageSource src = urlProfilo;
                sfondo.ImageSource = src;
                imageProfilo.Background = sfondo;

                FraseText.Text = appSettings["frase"].ToString();
  
            }
            else //non conosco i dati dell'utente da visualizzare
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    //faccio request PHP al DB con idUser
                    Uri myDBuri = new Uri("http://www.nearchat.altervista.org/profile.php");
                    HttpWebRequest profileRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    profileRequest.Method = "POST";
                    profileRequest.ContentType = "application/x-www-form-urlencoded";
                    profileRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), profileRequest);
                }
                else
                    MessageBox.Show("connection error, please retry later.");
                 
            }  
        }

        private void buttonModifica_Tap(object sender, GestureEventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() && appSettings.Contains("frase"))//c'è rete e ho i miei vecchi dati
                NavigationService.Navigate(new Uri("/ModificaProfilo.xaml", UriKind.Relative));//cambio della pagina
        }

        void GetRequestStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=4nn!eSupp0rt&ID=" + idUser;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
        }//GetRequestStreamCallback

        void GetResponsetStreamCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingProfilo(result));
            }
        }//GetResponsetStreamCallback

        void ParsingProfilo(string result)
        {
            if (result != "")
            {
                string[] ris = majorSplit(result);
                ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

                if (ris[0] == "ERRORE")
                {
                    MessageBox.Show(ris[1]);
                }
                else
                {
                    string data = ris[2];
                    string anno = data.Substring(0, 4);
                    data = data.Substring(5) + "/" + anno;
                    data = data.Replace('-', '/');

                    NameText.Text = ris[1];
                    InfoText.Text = ris[3] + " " + data;
                    imageURL=ris[4]; //l'URL della mia immagine

                    BitmapImage urlProfilo = new BitmapImage(new Uri(imageURL, UriKind.Absolute));
                    ImageBrush sfondo = new ImageBrush();
                    ImageSource src = urlProfilo;
                    sfondo.ImageSource = src;
                    imageProfilo.Background = sfondo;

                    FraseText.Text = ris[5];

                    if (appSettings["ID"].ToString() == ris[0])//è l'utente possessore
                    {
                        //salvo nell'applicazione
                        appSettings.Add("nascita", data);
                        appSettings.Add("sesso", ris[3]);
                        appSettings.Add("image", ris[4]);
                        appSettings.Add("frase", ris[5]);
                    }  
                }
            }
 
        }//ParsingProfilo

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
 
    }
}